<?php
//$conn = SqliteDB::instance('db/gushengwu.db');
class SqliteDB{
	private $dbname = '';
    
    //是否保存查询错误信息
    private $_save_errors = 1;
    
    //查询错误信息寄存条目上限
    private $_errors_amount = 5;
    
    //查询错误信息寄存器
    private $_errors = array();
    
    //查询语句寄存条目上限
    private $_ok_sqls_amount = 5;
    
    //查询语句寄存器
    private $_ok_sqls = array();
    
    //最近一条查询语句
    private $_last_sql;
    
    //类实体寄存器
    private static $_instance;
    
    //数据库实体寄存器
    private $_conn;
    
    function __construct(){
        ;
    }
    
	public static function get_instance(){
    	return self::$_instance;
    }
    
    public static function instance($dbname = null){
        //数据库对象实例化
        if (!$dbname) return false;
        self::$_instance = new self;
        self::$_instance->dbname = $dbname;
        //根据给定参数建立数据库连接
        self::$_instance->_conn = sqlite_open(self::$_instance->dbname);
        return self::$_instance;
    }
    
	public function query($sql,$result_type = SQLITE_ASSOC,$to_array = true){
		return self::$_instance->sqlInspecte($sql,$result_type,$to_array,1);
    }
    
	public function unbufferedQuery($sql,$result_type = SQLITE_ASSOC,$to_array = true){
		return self::$_instance->sqlInspecte($sql,$result_type,$to_array,0);
    }
    
	//sql分句隔断
    private function sqlInspecte($sql,$result_type,$to_array,$query_method){
        $sqls = trim($sql,';');
        //分句隔断点正则表达
        $preg = '/;(?=insert|delete|update|select|alter)/i';
        if (!preg_match($preg,$sqls)){
            return self::$_instance->querySql($sqls,$result_type,$to_array,$query_method);
        }else{
            $sqls = preg_split($preg,$sqls);
            foreach ($sqls as $sqls_v){
                $result = self::$_instance->querySql($sqls_v,$result_type,$to_array,$query_method);
                if ((false === $result) || (is_array($result) && $result) || (is_resource($result) && self::$_instance->fetchAll($result))){
                    return $result;
                }
            }
            return true;
        }
    }
    
	//主查询方法
    private function querySql($sql,$result_type = SQLITE_ASSOC,$to_array = true,$query_method = 1){
        //存储最近一条查询语句
        self::$_instance->_last_sql = $sql;
        
        if ($query_method){
            $result = sqlite_query($this->_conn,$sql);
        }else{
            $result = sqlite_unbuffered_query($this->_conn,$sql);
        }
        
        //query succeed
        if (false != $result){
            //存储最近一条成功的查询语句
            array_unshift(self::$_instance->_ok_sqls,$sql);
            if (self::$_instance->_ok_sqls_amount < count(self::$_instance->_ok_sqls)){
                array_pop(self::$_instance->_ok_sqls);
            }
            
            //返回查询结果集
            return (!is_resource($result) || !$to_array)?$result:self::$_instance->fetchAll($result,$result_type);
        }
        
        //query failed
        if (self::$_instance->_save_errors){
            //存储最近一条查询失败的错误信息
            array_unshift(self::$_instance->_errors,$sql."::ERROR::".self::$_instance->lastError());
            if (self::$_instance->_errors_amount < count(self::$_instance->_errors)){
                array_pop(self::$_instance->_errors);
            }
        }
        
        return false;
    }
    
    //结果集别名去除
    public function aliasClean($result){
    	$newResult = array();
    	foreach ($result as $key=>$field){
    		foreach ($field as $name=>$content){
    			$name = ltrim(strstr($name,'.'),'.');
    			$newResult[$key][$name] = $content;
    		}
    	}
    	return $newResult;
    }
    
    public function lastInsertRowid(){
    	return sqlite_last_insert_rowid($this->_conn);
    }
    
    public function last_sql(){
    	return self::$_instance->_last_sql;
    }
    
	//获取最近的成功的查询语句，参数$num为从1到保存上限的integer
    public function last_ok_sql($num = 1){
        if (--$num <= self::$_instance->_ok_sqls_amount){
            return !empty(self::$_instance->_ok_sqls[$num])?self::$_instance->_ok_sqls[$num]:'尚未有成功的查询';
        }else{
            return '错误的下标';
        }
    }
    
	//获取所有最近的成功的查询语句,return array
    public function last_ok_sqls(){
        if (!empty(self::$_instance->_ok_sqls)){
            return self::$_instance->_ok_sqls;
        }else{
            return '尚未有成功的查询';
        }
    }
    
    //获取最近的查询失败信息，参数$num为从1到保存上限的integer
    public function error($num = 1){
    	if (--$num <= self::$_instance->_errors_amount){
            return !empty(self::$_instance->_errors[$num])?self::$_instance->_errors[$num]:'暂无错误信息';
        }else{
            return '错误的下标';
        }
    }
    
	//获取所有最近的查询失败信息
    public function last_errors(){
        if (!empty(self::$_instance->_errors)){
            return self::$_instance->_errors;
        }else{
            return '暂无错误信息';
        }
    }
    
    private function lastError(){
    	if (is_string($error_code = sqlite_last_error($this->_conn))){
    		return $error_code;
    	}
    	return sqlite_error_string($error_code);
    }
    
    public function fetchAll($result,$result_type = SQLITE_ASSOC){
    	if (is_resource($result)){
    		return sqlite_fetch_all($result,$result_type);
    	}
    	return $result;
    }
    
    public function numRows($request){
    	//如果是结果集
        if (is_resource($request)){
            return sqlite_num_rows($request);
        }
        //如果是查询语句字符串
        if (is_string($request)){
        	if (is_resource($result = self::$_instance->query($request,SQLITE_ASSOC,false))){
        		return sqlite_num_rows($result);
        	}
        }
        //如果是结果集转换后的数组
        if (is_array($request)){
            return count($request);
        }
        
        return false;
    }
    
	public function close(){
        self::$_instance = '';
    }
    
    function __destruct(){
        if (is_resource($this->_conn)){
        	sqlite_close($this->_conn);
        }
    }
}